---
title: Introduction
description: GraphQL Code Generator is a plugin-based tool that helps you get the best out of your GraphQL stack. From back-end to front-end, GraphQL Code Generator automates the generation of typed Queries, Mutations and, Subscriptions for React, Vue, Angular, Next.js, Svelte, whether you are using Apollo Client, URQL or, React Query.
---

import { Tabs, Callout, Cards} from '@theguild/components'

# Introduction to GraphQL Code Generator

GraphQL Code Generator is a plugin-based tool that helps you get the best out of your GraphQL stack.

From back-end to front-end, GraphQL Code Generator automates the generation of:

- **Typed Queries, Mutations and, Subscriptions** for React, Vue, Angular, Next.js, Svelte, whether you are using Apollo Client, URQL or, React Query.
- **Typed GraphQL resolvers**, for any Node.js (GraphQL Yoga, GraphQL Modules, TypeGraphQL or Apollo) or Java GraphQL server.
- **Fully-typed Node.js SDKs, Apollo Android** support, and more!

## The perfect GraphQL Developer Experience

To illustrate how GraphQL Code Generator improves your developer experience, let's take a look at the front-end and back-end usage of the following schema:

```graphql filename="schema.graphql"
type Author {
  id: Int!
  firstName: String!
  lastName: String!
  posts(findTitle: String): [Post]
}

type Post {
  id: Int!
  title: String!
  author: Author
}

type Query {
  posts: [Post]
}
```

The following sections showcase why GraphQL Code Generator is a game-changer for your GraphQL Stack.

### From the Frontend

Most client-side implementations without GraphQL Code Generator would query the API as showcased in the following examples:

<Tabs items={['URQL React', 'React Query', 'Vue Apollo', 'Angular Apollo', 'Svelte Apollo']}>
<Tabs.Tab>
```tsx
import { useQuery } from 'urql'

interface PostsQuery {
  posts: {
    id: string
    title: string
    author?: {
      id: string
      firstName: string
      lastName: string
    }
  }[]
}

const postsQueryDocument = /* GraphQL */ `
  query Posts {
    posts {
      id
      title
      author {
        id
        firstName
        lastName
      }
    }
  }
`

const Posts = () => {
  const [result] = useQuery<PostsQuery>({ query: postsQueryDocument })

  // …
}
```
</Tabs.Tab>

<Tabs.Tab>
```tsx
import { request, gql } from 'graphql-request'
import { useQuery } from '@tanstack/react-query'

interface PostsQuery {
  posts: {
    id: string
    title: string
    author?: {
      id: string
      firstName: string
      lastName: string
    }
  }[]
}

const postsQueryDocument = gql`
  query Posts {
    posts {
      id
      title
      author {
        id
        firstName
        lastName
      }
    }
  }
`

const Posts = () => {
  const { data } = useQuery<PostsQuery>('posts', async () => {
    const { posts } = await request(endpoint, postsQueryDocument)
    return posts
  })

  // …
}
```
</Tabs.Tab>

<Tabs.Tab>
```vue
<template>
  <div class="apollo">
    <!-- UI … -->
  </div>
</template>

<script lang="ts">
interface PostQueryVariables {
  id: string
}

export default {
  apollo: {
    post: {
      query: gql`
        query ($id: ID!) {
          post(id: $id) {
            id
            title
            author {
              id
              firstName
              lastName
            }
          }
        }
      `,
      variables: { id: 1 } as PostQueryVariables
    }
  },
  data() {
    return {
      post: undefined
    }
  }
}
</script>
```
</Tabs.Tab>

<Tabs.Tab>
```tsx
const GET_POSTS = gql`
  query Posts {
    posts {
      id
      title
      author {
        id
        firstName
        lastName
      }
    }
  }
`

interface Post {
  id: string
  title: string
  author?: {
    id: string
    firstName: string
    lastName: string
  }
}

@Component({ /* … */ })
class PostsComponent implements OnInit, OnDestroy {
  posts: Post[]

  private querySubscription: Subscription

  ngOnInit() {
    this.querySubscription = this.apollo
      .watchQuery({ query: GET_POSTS })
      .valueChanges.subscribe(({ data }) => {
        this.posts = data.posts as Post[]
      })
  }
  ngOnDestroy() {
    this.querySubscription.unsubscribe()
  }
}
```
</Tabs.Tab>

<Tabs.Tab>
```svelte
<script lang="ts">
  import { query } from 'svelte-apollo'

  const postsQueryDocument = gql`
    query Posts {
      posts {
        id
        title
        author {
          id
          firstName
          lastName
        }
      }
    }
  `

  const posts = query(postsQueryDocument)
</script>

<ul>
  <!-- UI … -->
</ul>
```
</Tabs.Tab>
</Tabs>

Manually maintaining the GraphQL operation types or the complete absence of types can lead to many issues:

- **outdated typing** (regarding the current Schema)

- **typos**

- **partial typing** of data (not all Schema&apos;s fields has a corresponding type)

The strength of your frontend application types is based on your data types.
Any mistake on your manually maintained data types ripples in many of your components.

For this reason, automating and generating the typing of your GraphQL operations will both improve the developer
experience and stability of your stack.

After installing GraphQL Code Generator:

```sh npm2yarn
npm i graphql
npm i -D typescript @graphql-codegen/cli
```

and providing a simple configuration:

```ts filename="codegen.ts"
import type { CodegenConfig } from '@graphql-codegen/cli'

const config: CodegenConfig = {
   schema: 'https://localhost:4000/graphql',
   documents: ['src/**/*.tsx'],
   generates: {
      './src/gql/': {
        preset: 'client',
      }
   }
}
export default config
```

You will no longer need to maintain TypeScript types:

<Tabs items={['URQL React', 'React Query', 'Vue Apollo', 'Angular Apollo', 'Svelte Apollo']}>
<Tabs.Tab>
```tsx
import { useQuery } from 'urql'
import { graphql } from './gql/gql'

// postsQueryDocument is now fully typed!
const postsQueryDocument = graphql(/* GraphQL */ `
  query Posts {
    posts {
      id
      title
      author {
        id
        firstName
        lastName
      }
    }
  }
`)

const Posts = () => {
  // URQL's `useQuery()` knows how to work with typed graphql documents
  const [result] = useQuery({ query: postsQueryDocument })

  // `result` is fully typed!
  // …
}
```
</Tabs.Tab>

<Tabs.Tab>
```tsx
import { request } from 'graphql-request'
import { useQuery } from '@tanstack/react-query'
import { graphql } from './gql/gql'

// postsQueryDocument is now fully typed!
const postsQueryDocument = graphql(/* GraphQL */ `
  query Posts {
    posts {
      id
      title
      author {
        id
        firstName
        lastName
      }
    }
  }
`)

const Posts = () => {
  // React Query `useQuery()` knows how to work with typed graphql documents
  const { data } = useQuery<PostsQuery>('posts', async () => {
    const { posts } = await request(endpoint, postsQueryDocument)
    return posts
  })

  // `data` is fully typed!
  // …
}
```
</Tabs.Tab>

<Tabs.Tab>
```vue
<script setup lang="ts">
import { useQuery } from '@vue/apollo-composable';
import { graphql } from './gql/gql';
import FilmItem from './components/FilmItem.vue';
import { computed } from 'vue';
const { result } = useQuery(
  graphql(/* GraphQL */ `
    query Posts {
      posts {
        id
        title
        author {
          id
          firstName
          lastName
        }
      }
    }
  `),
);

// `posts` is properly typed!
const posts = computed(() => result.value?.posts);
</script>

<template>
  <ul>
    <li v-for="film of films"><FilmItem :film="film" /></li>
  </ul>
</template>
```
</Tabs.Tab>

<Tabs.Tab>
```tsx
import { PostsGQL, PostsQuery } from './graphql'
import { Observable } from 'rxjs'
import { map } from 'rxjs/operators'

@Component({ /* … */ })
export class PostsComponent {
  posts: Observable<PostsQuery['posts']>

  constructor(postsGQL: PostsGQL) {
    this.posts = postsGQL.watch().valueChanges.pipe(map(result => result.data.posts))
  }
}
```
</Tabs.Tab>

<Tabs.Tab>
```svelte
<script lang="ts">
  import { Posts } from '../graphql/generated'

  // `posts` is fully typed, also are `Posts()` options!
  const posts = Posts()
</script>

<ul>
  <!-- UI … -->
</ul>
```
</Tabs.Tab>
</Tabs>

Now, with simple configuration and an npm/yarn script, a front-end developer benefits from:

- **up-to-date typings**

- **autocompletion on all queries, mutations and, subscription variables and results**

- **less boilerplate** (thanks to full code generation such as React hooks generation)

<Callout>
**Operations and fragments must have unique names**

GraphQL Code Generator checks for this automatically and will let you know if you have any conflicts.
</Callout>

<Callout>
**How does GraphQL Code Generator work?**

More details on the inner working of GraphQL Code Generator are available on [this page](/docs/advanced/how-does-it-work).
</Callout>

### To the Backend

Most GraphQL API resolvers remain untyped or wrongly typed which, leads to multiple issues:

- resolvers are not compliant with the schema definition

- typos in the resolvers' function type signature

For this reason, GraphQL Code Generator provides multiple plugins that help you automate the generation of resolvers' typings.

Here are an example of a GraphQL API leveraging GraphQL Code Generator resolvers typings (based on the `schema.graphql` above):

<Tabs items={['Apollo Server', 'GraphQL Yoga', 'GraphQL Modules']}>
<Tabs.Tab>
```ts
import { readFileSync } from 'node:fs'
import { ApolloServer } from 'apollo-server'
import { Resolvers } from './resolvers-types'

const typeDefs = readFileSync('./schema.graphql', 'utf8')

const resolvers: Resolvers = {
  Query: {
    // typed resolvers!
  }
}

const server = new ApolloServer({ typeDefs, resolvers })

// The `listen` method launches a web server
server.listen().then(({ url }) => {
  console.log(`🚀  Server ready at ${url}`)
})
```
</Tabs.Tab>

<Tabs.Tab>
```ts
import { readFileSync } from 'node:fs'
import { createServer } from 'node:http'
import { createYoga, createSchema } from 'graphql-yoga'
import { Resolvers } from './resolvers-types'

const typeDefs = readFileSync('./schema.graphql', 'utf8')

const resolvers: Resolvers = {
  Query: {
    // typed resolvers!
  }
}

const schema = createSchema({ typeDefs, resolvers })
const yoga = createYoga({ schema })
const server = createServer(yoga)

server.listen(4000, () => {
  console.log('GraphQL Server is listening on http://localhost:4000/graphql');
})
```
</Tabs.Tab>

<Tabs.Tab>
Given the following structure:

```
- src/
  - modules/
    - user/
      - resolvers.ts
      - typedefs/
        - user.graphql
    - product/
      - resolvers.ts
      - typedefs/
        - product.graphql
```

The User module resolvers would be:

```ts filename="src/modules/user/resolvers.ts"
import { UsersModule } from './generated-types/module-types'

export const resolvers: UsersModule.Resolvers = {
  // Here, you can implement only the types and fields defined in your module!
}
```
</Tabs.Tab>
</Tabs>

## What's next?

After unstanding the basic concepts of GraphQL Code Generator, you can start setting it up within your project.
If your stack is not listed below, please refer to [our plugin overview](/plugins).

### Client-Side GraphQL

Choose your existing setup or preference to get started.

<Cards>
  <Cards.Card arrow title="Vanilla TypeScript" href="/docs/guides/vanilla-typescript" />
  <Cards.Card arrow title="React Query" href="/docs/guides/react-query" />
  <Cards.Card arrow title="React / Vue" href="/docs/guides/react-vue" />
  <Cards.Card arrow title="Angular" href="/docs/guides/angular" />
  <Cards.Card arrow title="Svelte" href="/docs/guides/svelte" />
</Cards>

### Server-Side GraphQL


<Cards>
  <Cards.Card
    arrow
    title="GraphQL Yoga with Server Preset"
    href="/docs/guides/graphql-server-apollo-yoga-with-server-preset"
  />
   <Cards.Card
    arrow
    title="Apollo Server with Server Preset"
    href="/docs/guides/graphql-server-apollo-yoga-with-server-preset"
  />
  <Cards.Card arrow title="Apollo and Yoga server" href="/docs/guides/graphql-server-apollo-yoga" />
  <Cards.Card arrow title="GraphQL Modules" href="/docs/guides/graphql-modules" />
</Cards>


### Troubleshooting

If you are experiencing any issues, you can reach us via the following channels:

- Found a bug? [report it in our GitHub repo](https://github.com/dotansimha/graphql-code-generator)
- Need help or have a question? You can use the live chat box in the corner of the screen, [ask it in our GitHub Discussions page](https://github.com/dotansimha/graphql-code-generator/discussions) or [reach out to us directly in our Discord](http://bit.ly/guild-chat)
- We have more awesome [open source tools](https://github.com/the-guild-org/Stack)!
- You can [visit our website](https://the-guild.dev) for more information about us and what we do
